package com.liqw.crawler.controller;

import com.liqw.crawler.request.HouseReq;
import com.liqw.crawler.response.HouseRsp;
import com.liqw.crawler.model.House;
import com.liqw.crawler.convert.HouseConvert;
import jakarta.validation.Valid;
import com.liqw.crawler.repository.HouseRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.persistence.EntityNotFoundException;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.springframework.web.bind.annotation.CrossOrigin;

@Slf4j
@RestController
@RequestMapping("/api/houses")
@RequiredArgsConstructor
@Tag(name = "House API", description = "房源信息管理接口")
@CrossOrigin(origins = "http://localhost:5175")
public class HouseController {

    private final HouseRepository houseRepository;
    private final HouseConvert houseConvert;

    @GetMapping("")
    public List<HouseRsp> getAllHouses() {
        return houseRepository.findAll().stream()
                .map(HouseConvert.INSTANCE::toRsp)
                .collect(Collectors.toList());
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取房源", description = "通过房源ID查询具体房源信息")
    @ApiResponse(responseCode = "404", description = "房源不存在")
    public ResponseEntity<HouseRsp> getHouseById(
            @Parameter(description = "房源ID") @PathVariable String id) {
        House house = houseRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("House not found with id: " + id));
        return ResponseEntity.ok(HouseConvert.INSTANCE.toRsp(house));
    }

    @PostMapping
    @Operation(summary = "创建新房源", description = "添加新的房源信息到系统")
    @ApiResponse(responseCode = "201", description = "房源创建成功")
    public ResponseEntity<HouseRsp> createHouse(
            @Parameter(description = "房源信息") @Valid @RequestBody HouseReq houseReq) {
        log.info("Received create house request: {}", houseReq);
        try {
            House house = HouseConvert.INSTANCE.toEntity(houseReq);
            log.info("Converted house entity: {}", house);
            House savedHouse = houseRepository.save(house);
            return new ResponseEntity<>(HouseConvert.INSTANCE.toRsp(savedHouse), HttpStatus.CREATED);
        } catch (Exception e) {
            log.error("Failed to create house: {}", e.getMessage(), e);
            throw e;
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新房源信息", description = "根据ID更新已有房源信息")
    @ApiResponse(responseCode = "200", description = "房源更新成功")
    @ApiResponse(responseCode = "404", description = "房源不存在")
    public ResponseEntity<HouseRsp> updateHouse(
            @Parameter(description = "房源ID") @PathVariable String id,
            @Parameter(description = "更新后的房源信息") @Valid @RequestBody HouseReq houseReq) {
        House existingHouse = houseRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("House not found with id: " + id));

        existingHouse = houseConvert.toEntity(houseReq);
        House updatedHouse = houseRepository.save(existingHouse);
        return ResponseEntity.ok(HouseConvert.INSTANCE.toRsp(updatedHouse));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除房源", description = "根据ID删除房源信息")
    @ApiResponse(responseCode = "204", description = "房源删除成功")
    @ApiResponse(responseCode = "404", description = "房源不存在")
    public ResponseEntity<Void> deleteHouse(
            @Parameter(description = "房源ID") @PathVariable String id) {
        House house = houseRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("House not found with id: " + id));

        houseRepository.delete(house);
        return ResponseEntity.noContent().build();
    }

}
